package mytweetdiary;

import com.google.appengine.api.users.User;
import mytweetdiary.ds.*;

import javax.jdo.PersistenceManager;
import twitter4j.Twitter;
import twitter4j.TwitterFactory;
import twitter4j.http.RequestToken;
import twitter4j.http.AccessToken;

public class TwitterManager {

	private static String consumerKey = "5EpXlWH4YGVpKZdVOrK1w";
	private static String consumerSecret = "ZUsVUhFp5dAE7wn1DfovZJLhSFTgZatI7xX3IKD8A";

	private User user;
	private TwitterInfo twitterInfo;

	public TwitterManager(User user) {
		this.user = user;
		twitterInfo = getTwitterInfoFromDS(user);
		if (twitterInfo == null) {
			createTwitterInfo();
		}
	}

	public Twitter getTwitterInstance() {
		if (twitterInfo.isAuthorized() == true) {
			return (new TwitterFactory()).getOAuthAuthorizedInstance(
					consumerKey, consumerSecret, new AccessToken(twitterInfo
							.getAccessToken(), twitterInfo.getAccessSecret()));
		} else {
			return (new TwitterFactory()).getOAuthAuthorizedInstance(
					consumerKey, consumerSecret);
		}
	}

	public TwitterInfo getTwitterInfo() {
		return twitterInfo;
	}

	public boolean isAuthorized() {
		return twitterInfo.isAuthorized();
	}

	private void createTwitterInfo() {
		twitterInfo = new TwitterInfo(user);
		saveTwitterInfo();
	}

	private void saveTwitterInfo() {
		PersistenceManager pm = PMF.get().getPersistenceManager();

		try {
			pm.makePersistent(twitterInfo);
		} finally {
			pm.close();
		}
	}

	private TwitterInfo getTwitterInfoFromDS(User user) {
		TwitterInfo twitterInfo = null;
		PersistenceManager pm = PMF.get().getPersistenceManager();
		try {
			twitterInfo = pm.getObjectById(TwitterInfo.class, user.getEmail());
		} catch (javax.jdo.JDOObjectNotFoundException e) {
			return null;
		} finally {
			pm.close();
		}
		return twitterInfo;
	}

	public void clearTwitterInfo() {
		twitterInfo.setAccessToken(null);
		twitterInfo.setAccessSecret(null);
		twitterInfo.setRequestToken(null);
		twitterInfo.setRequestSecret(null);
		saveTwitterInfo();
	}
	
	public void saveRequestToken(RequestToken requestToken) {
		twitterInfo.setRequestToken(requestToken.getToken());
		twitterInfo.setRequestSecret(requestToken.getTokenSecret());
		saveTwitterInfo();
	}
	
	public void saveAccessToken(AccessToken accessToken) {
		twitterInfo.setRequestToken(null);
		twitterInfo.setRequestSecret(null);
		twitterInfo.setAccessToken(accessToken.getToken());
		twitterInfo.setAccessSecret(accessToken.getTokenSecret());
		saveTwitterInfo();
	}
	
	public RequestToken getRequestToken() {
		if (twitterInfo.getRequestToken() == null) {
			return null;
		} else {
			return new RequestToken(twitterInfo.getRequestToken(), twitterInfo
					.getRequestSecret());
		}
	}
}
